package com.semidata.trp.business.report;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import com.semidata.trp.message.business.Report;

public class ReportData implements Cloneable {

    private long time;

    private Map<String, MonitorReportData> table = new HashMap<>();

    public ReportData() {
        time = System.currentTimeMillis();
    }

    public ReportData(File file) {
        try {
            build(Report.SummaryReport.parseFrom(new FileInputStream(file)));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public ReportData(Report.SummaryReport data) {
        build(data);
    }

    private void build(Report.SummaryReport data) {
        try {

            this.time = data.getTime();

            for (Report.MonitorReport item : data.getReportList()) {
                table.put(item.getServer(), new MonitorReportData(item));
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public long getTime() {
        return time;
    }

    public void setTime(long time) {
        this.time = time;

    }

    public synchronized Set<MonitorReportData> getMonitorReportData() {

        Set<MonitorReportData> set = new HashSet<>();

        for (MonitorReportData value : table.values()) {
            set.add(value);
        }
        return set;
    }

    public synchronized void putMonitorReportData(MonitorReportData data) {
        MonitorReportData value = table.get(data.getServer());
        if (value == null || data.getTime() > value.getTime()) {
            table.put(data.getServer(), data);
        }
        time = System.currentTimeMillis();

    }

    private Report.SummaryReport dump() {
        Report.SummaryReport.Builder builder = Report.SummaryReport.newBuilder();
        builder.setTime(time);
        for (MonitorReportData item : getMonitorReportData()) {
            builder.addReport(item.getData());
        }
        return builder.build();
    }

    public void dump(File file) {
        byte[] bytes = dump().toByteArray();
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(file);
            out.write(bytes);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public ReportData clone() {
        return new ReportData(this.dump());
    }

}
